//
//  XCOauthViewController.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/2/27.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit
import SVProgressHUD
class XCOauthViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
view.backgroundColor = UIColor.redColor()
        
 //MARK:- 设置导航条上的按钮
  /// 设置导航条上的按钮
  setUpNavigationBar()
        let url = NSURLRequest(URL: XCNetworkingTool.sharedInstance.oauthLoginUrl())
        print("url:\(url)")
        webView.loadRequest(url)
    }

    func setUpNavigationBar (){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "oauthFill");
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
    }
    

    //MARK: - 实现导航条上按钮的方法
    func oauthFill() {
        let js = "document.getElementById('userId').value='13192926342';document.getElementById('passwd').value='qq2534412123'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    func cancel() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: - 懒加载 webView
    lazy var webView:UIWebView =  UIWebView()
   
}




// MARK:- 实现 webView 的代理方法
extension XCOauthViewController:UIWebViewDelegate {
    //webView 开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载登录界面", maskType: SVProgressHUDMaskType.Black)
    }
    // webView 加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
//
        SVProgressHUD.dismiss()
    }
    // webView 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
        // 没有网络错误的code = 1009
        if error?.code != 102 {
            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
        }


    }
    
    // webView 询问我们是否要加载某个请求，true 去加载  或者 false 不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        
        let urlString = request.URL?.absoluteString
        print("urlString:\(urlString)")
        // 1. 判断是否是回调地址开头.是回调地址开头,表示用点击的是授权或取消按钮
        if urlString!.hasPrefix(XCNetworkingTool.sharedInstance.redirect_uri){
            let query = request.URL?.query
            
            let codeString = "code="
            // 判断query是以code=开头表示点击的是 授权按钮, 其它的点击的是 取消 按钮
            // query:?后面的请求参数
            
            if query!.hasPrefix(codeString){// 点击了授权按钮
                let queryNS = query! as NSString
        // 2. 授权按钮,截取code的值
                let code = queryNS.substringFromIndex(codeString.characters.count)
                print("取得了code: \(code)")
//        XCUSerAccountViewModel.sharedInstance.loadAccessToken(code)
     print("\n\t----------code : \(code)\n\t")
// MARK: -获取取得了code
//        3.1 调用XCUserAccountViewModel的方法去加载请求
                XCUSerAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallBack: { (error) -> () in
                 // 3.9 判断请求AccessToken 是否出错
                    if error != nil{
                        print("获取AccessToken 失败\(error)")
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            // 关闭控制器
                            self.cancel()
                            
                            
                        })
                        
                    }
                    // 4.0 保存账号成功
                self.cancel()
                    
             // 显示主界面了
             let App =  UIApplication.sharedApplication().delegate as! AppDelegate
                    App.window?.rootViewController = XCMainViewController()
                })
               
            }else{// 点击了授权取消按钮
                cancel()
               
            }
            
            return false
            
        }else{
            return true
            
        }
    
    }
}
